package com.kinptm.masterclock.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ViewFlipper;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.doomonafireball.betterpickers.dhmspicker.DhmsPickerBuilder;
import com.doomonafireball.betterpickers.dhmspicker.DhmsPickerDialogFragment;
import com.kinptm.masterclock.R;
import com.kinptm.masterclock.adapter.HolderViewFiller;
import com.kinptm.masterclock.adapter.item.TimerRecordItemBuilder;
import com.kinptm.masterclock.bean.TimerRecord;
import com.kinptm.masterclock.db.DbHelper;
import com.kinptm.masterclock.utils.AlarmUtil;
import com.kinptm.masterclock.utils.ViewUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by pc on 13-11-7.
 */
public class TimerFragment extends SherlockFragment implements DhmsPickerDialogFragment.DhmsPickerDialogHandler, View.OnClickListener {
    private static final int MENU_START_ID = Menu.FIRST;
    private static final int MENU_RESTART_ID = Menu.FIRST + 1;
    private static final int MENU_DELETE_ID = Menu.FIRST + 2;
    private ListView mTimerListView;
    private HolderViewFiller<TimerRecord> mHolderViewFiller;
    private List<TimerRecord> mTimerRecords;
    private Timer mTimer;

    private ViewFlipper mSwapViewFlipper;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mHolderViewFiller.exportAdapter(mTimerListView).notifyDataSetChanged();
        }
    };

    public static TimerFragment newInstance() {
        TimerFragment fragment = new TimerFragment();
//        Bundle bundle = new Bundle();
//        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_timer, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTimerListView = ViewUtil.findView(view, R.id.timer_list);
        mSwapViewFlipper = ViewUtil.findView(view, R.id.swap_layout_vf);
        ViewUtil.findViewAndClick(view, R.id.timer_add_btn, this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        mTimerRecords = DbHelper.getInstance().getTimerRecordDao().queryForAll();

        mHolderViewFiller = new HolderViewFiller<TimerRecord>(getLayoutInflater(savedInstanceState), new TimerRecordItemBuilder());
        mHolderViewFiller.update(mTimerListView, mTimerRecords);

        mTimer = new Timer();
        UpdateTimerTask timerTask = new UpdateTimerTask();
        mTimer.schedule(timerTask, 0, 1000);

        checkSwapViewFlipper();
    }

    private void checkSwapViewFlipper() {
        if (mTimerRecords.isEmpty()) {
            mSwapViewFlipper.setDisplayedChild(1);
        } else {
            mSwapViewFlipper.setDisplayedChild(0);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_timer, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_timer_add:
                showAddTimerDialog();
                break;
            case R.id.action_timer_cates:

                break;
            case R.id.action_timer_order:

                break;
            case R.id.action_timer_start_all:

                break;
            case R.id.action_timer_delete_all:

                break;
            case R.id.action_timer_filter:

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showAddTimerDialog() {
        DhmsPickerBuilder dhmsPickerBuilder = new DhmsPickerBuilder().
                setFragmentManager(getFragmentManager()).
                setStyleResId(R.style.BetterPickersDialogFragment_Light);
        dhmsPickerBuilder.show();
        dhmsPickerBuilder.addDhmsPickerDialogHandler(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerForContextMenu(mTimerListView);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterForContextMenu(mTimerListView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
    }

    @Override
    public void onDialogDhmsSet(int reference, int hours, int minutes, int seconds) {
        TimerRecord record = new TimerRecord(getActivity(),hours, minutes, seconds);
        record.setTitle("计时器");
        record.setRemark("你设的倒计时,倒计结束啦! 快点做该做的事吧!");
        record.setEnable(true);
        DbHelper.getInstance().getTimerRecordDao().createOrUpdate(record);
        mHolderViewFiller.add(mTimerListView, record);
        AlarmUtil.plan2AlarmTimer(record);
        checkSwapViewFlipper();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        int itemPosition = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
        TimerRecord record = (TimerRecord) mTimerListView.getItemAtPosition(itemPosition);
        if (!record.isEnable()) {
            menu.add(0, MENU_START_ID, 0, "启动");
        }
        if (record.isEnable() && record.isFinish()) {
            menu.add(0, MENU_RESTART_ID, 0, "重新计时");
        }
        menu.add(0, MENU_DELETE_ID, 1, "删除");


    }

    @Override
    public boolean onContextItemSelected(android.view.MenuItem item) {
        int itemPosition = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
        TimerRecord record = (TimerRecord) mTimerListView.getItemAtPosition(itemPosition);
        switch (item.getItemId()) {
            //启动 , 重启
            case MENU_START_ID:
            case MENU_RESTART_ID:
                record.setEnable(true);
                record.setFinish(false);
                AlarmUtil.plan2AlarmTimer(record);
                DbHelper.getInstance().getTimerRecordDao().update(record);
                break;
            //删除
            case MENU_DELETE_ID:
                DbHelper.getInstance().getTimerRecordDao().delete(record);

                mTimerRecords.remove(itemPosition);
                mHolderViewFiller.exportAdapter(mTimerListView).notifyDataSetChanged();

                AlarmUtil.cancel2AlarmTimer(record);
                break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.timer_add_btn:
                showAddTimerDialog();
                break;
        }
    }

    class UpdateTimerTask extends TimerTask {
        @Override
        public void run() {
            Message message = mHandler.obtainMessage(1);
            mHandler.sendMessage(message);
        }
    }
}